let express = require('express')
let router = express.Router()

let mysqlHelper = require('../utils/mysqlHelper.js')
const utils = require('../utils/utils.js')

// 查询列表 maoyuan
router.get('/list', async function (req, res, next) {
    let result = {}
    var temp_parent = { "id": 0, "children": [] };//新建id为0的对象做为森林的根
    try {
        let keyword = utils.getQueryValue(req.query.keyword)
        let sqlWhere = (keyword != '' ? " where orgName like '%" + keyword + "%'" : "")
        let sqlStr = "select org.orgid as id,parentId,orgName as label,DATE_FORMAT(date,'%Y-%m-%d %H:%i:%s') as date,remark,status,orderinlist as sort,org.contactorIds,con.contactors \
                      from sys_organization org Left join    \
                      (SELECT a.orgId, a.contactorIds, GROUP_CONCAT(b.name ORDER BY b.userId) contactors   \
                      FROM    sys_organization a   \
                      INNER JOIN sys_user b ON FIND_IN_SET(b.userId, a.contactorIds) > 0    \
                      GROUP   BY a.orgId, a.contactorIds) con on org.orgId=con.orgId "+ sqlWhere + " order by parentId, orderinlist"
        alldata = await mysqlHelper.query(sqlStr)
        let data = []
        data.push(temp_parent)

        result.code = 200
        result.data = getAllChild(data);
        result.success = true
    } catch (err) {
        result.code = 400
        result.success = false
        result.err = err.message
    }
    res.json(result)


    //find some item all child
    function findItemChild(item) {
        var arrayList = [];
        for (var i in alldata) {
            if (alldata[i].parentId == item.id) {
                alldata[i].check = false
                arrayList.push(alldata[i]);
            }
        }
        return arrayList;
    }

    //get all child
    function getAllChild(array) {
        var childList = findItemChild(array[0]);
        if (childList == null) {
            return [];
        }
        else {
            for (var j in childList) {
                childList[j].children = [];
                childList[j].children = getAllChild([childList[j]]);
            }
            array[0].children = childList;
        }
        return childList;
    }

})

// Form修改字段 maoyuan
router.post('/post', async function (req, res, next) {
    let result = {}
    try {
        let id = utils.getQueryValue(req.body.id)
        let contactorIds = utils.getQueryValue(req.body.contactorIds)
        if (contactorIds!='')
            contactorIds = contactorIds.join()
        let sqlStr = ""
        if (id == '') {  // 新增
            sqlStr = "INSERT INTO sys_organization (orgName,parentId,remark,status,orderinlist,contactorIds) VALUES('"
                + req.body.label + "'," + (req.body.parentId == '' ? 0 : req.body.parentId)
                + ",'" + req.body.remark + "'," + req.body.status + "," + req.body.sort + ",'"+contactorIds+"')"
        } else {  // 编辑
            sqlStr = "update sys_organization set orgName='" + req.body.label + "',parentId=" + req.body.parentId
                + ",remark='" + req.body.remark + "',status=" + req.body.status + ",orderinlist=" + req.body.sort + ",contactorIds='"+contactorIds+"',date=now() where orgId=" + req.body.id
        }
        result.code = 200
        result.data = await mysqlHelper.query(sqlStr)
        result.success = true
    } catch (err) {
        result.code = 400
        result.success = false
        result.err = err.message
    }
    res.json(result)
})

// 删除 maoyuan
router.delete('/', async function (req, res, next) {
    let result = {}
    try {
        let sqlStr = "DELETE FROM sys_organization WHERE orgId in (" + req.body.ids + ")"
        result.code = 200
        result.data = await mysqlHelper.query(sqlStr)
        result.success = true
    } catch (err) {
        result.code = 400
        result.success = false
        result.err = err.message
    }
    res.json(result)
})

module.exports = router
